package com.pxmeta.dynamic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.common.enums.DynamicEnum;
import com.pxmeta.dynamic.entity.Topic;
import com.pxmeta.dynamic.entity.SearchHistory;
import com.pxmeta.dynamic.mapper.TopicMapper;
import com.pxmeta.dynamic.mapper.TopicSearchHistoryMapper;
import com.pxmeta.dynamic.service.ISearchHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wcl
 * @since 2022-07-12
 */
@Service
@RequiredArgsConstructor
public class SearchHistoryServiceImpl extends ServiceImpl<TopicSearchHistoryMapper, SearchHistory> implements ISearchHistoryService {

    private final TopicMapper topicMapper;

    /**
     * 保存搜索记录
     * @param userId
     * @param circleId
     * @param name
     * @param type
     */
    @Override
    public void saveSearch(Long userId, Long circleId, String name, Integer type) {
        Long targetId = null;
        if (DynamicEnum.TYPE_TOPIC.getType().equals(type)){
            //查询该话题是否存在
            LambdaQueryWrapper<Topic> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(Topic::getCircleId, circleId)
                    .eq(Topic::getName,name);
            Topic topic = topicMapper.selectOne(wrapper);
            if (topic == null){
                return;
            }
            targetId = topic.getId();
        }
        SearchHistory history = getSearchByName(userId, circleId, name, type);
        if (history != null){
            history.setTargetId(targetId);
            this.updateById(history);
        }else {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setTargetId(targetId);
            searchHistory.setSearchName(name);
            searchHistory.setCircleId(circleId);
            searchHistory.setUserId(userId);
            searchHistory.setType(type);
            this.save(searchHistory);
        }
    }


    private SearchHistory getSearchByName(Long userId, Long circleId, String name, Integer type){

        LambdaQueryWrapper<SearchHistory> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SearchHistory::getUserId,userId)
                .eq(SearchHistory::getCircleId, circleId)
                .eq(SearchHistory::getSearchName,name)
                .eq(SearchHistory::getType,type);

        return this.getOne(wrapper,false);
    }
}
